/**
 * @Description 登陆view
 * @author lirenyi
 * @update 2016-06-10
 */
define(function(require, exports, modules) {
	'use strict';

	require('css!assets/css/login/login.css');
	require('assets/plugins/md5.js');
	require('http://static.geetest.com/static/tools/gt.js');	//极客SDK

	var template = require('text!./tpl.login.html'), 
		util = require('util');
	var View = Backbone.View.extend({
		el : '#page',
		events : {
			'click .login .forgetBtn':'openForgetPassword',
			'click #forgetPassword .closefgpwBtn':'closeForgetPassword',
			'click #forgetPassword .fgpwBtn':'changePassword',
			'click #forgetPassword .send-captcha':'sendCaptcha',
			'click #alertMsg .only-confirm':'closeMsg',
			'click .loginBtn':'toHome',
			'click .common-loading' : 'hideGt'
		},
		initialize : function() {
			this.template = _.template(template);
			this.render();
		},
		render : function() {
			this.$el.html(this.template());
			this.getOs();
			this.canvas();
			this.setting();
		},
		openForgetPassword:function(){
			this.$el.append(util.loadTpl($('#forgetPassworgTpl')));
			var w = $('#forgetPassword .fgpw-board').width();
			var h = w*598/602;
			$('#forgetPassword .fgpw-board').height(h);
			$('#forgetPassword .fgpw-board').css({top: 'calc((100% - '+h+'px)/2)'});
		},
		closeForgetPassword:function(){
			$('#forgetPassword').remove();
		},
		changePassword:function(){
			var _this = this,
				phone = $.trim($('input[name="fphone"]').val()),
				vCode = $.trim($('input[name="fcaptcha"]').val()),
				newPassword = $.trim($('input[name="newPassword"]').val()),
				confirmPassword = $.trim($('input[name="confirmPassword"]').val());
			if(!phone){
				this.alertMsg('请输入手机号！');
				return;
			}
			if(!vCode){
				this.alertMsg('请输入验证码！');
				return;
			}
			if(!newPassword){
				this.alertMsg('请输入新密码！');
				return;
			}
			if(!confirmPassword){
				this.alertMsg('请输入确认密码！');
				return;
			}
			loadingShow();
			$('body').append('<div class="gt"></div>');
			var handlerPopupMobile = function (captchaObj) {
		        // 将验证码加到id为captcha的元素里
		        captchaObj.appendTo(".gt");
		        //拖动验证成功后两秒(可自行设置时间)自动发生跳转等行为
		        captchaObj.onSuccess(function () {
		        	$(".gt").remove();
		            var validate = captchaObj.getValidate();
		            jsonpGet(
	            		util.NDNserver + "/forgetPassword", // 进行二次验证
		                {
		                    // 二次验证所需的三个值
		                	phone: phone,
		                	actionId: _this.actionId,
		                	vCode : vCode,
		                	newPassword: hex_md5(newPassword),
		                    geetest_challenge: validate.geetest_challenge,
		                    geetest_validate: validate.geetest_validate,
		                    geetest_seccode: validate.geetest_seccode
		                },
		                'forgetPassword',
		                function (json) {
		                	if(json.code == '1'){
		                		$(".common-loading").remove();
								_this.closeForgetPassword();
								_this.alertMsg('设置成功');
							}else{
								$(".common-loading").remove();
								_this.alertMsg('设置失败');
							}
		                }
		            );
		        });
		        // 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
		    };
		    jsonpGet(
		        // 获取id，challenge，success（是否启用failback）
		        util.NDNserver + "/geetestRegister", 
		        {t: new Date().getTime()},	// 加随机数防止缓存
		        'geetestRegister',
		        function (json) {
		            // 使用initGeetest接口
		            // 参数1：配置参数
		            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
		        	var data = $.parseJSON(json.data);
		            initGeetest({
		                gt: data.gt,
		                challenge: data.challenge,
		                offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
		                // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
		            }, handlerPopupMobile);
		        }
		    );
			/*if(vCode.length > 0 && phone.length>0 &&newPassword.length > 0 && newPassword == confirmPassword){
				loadingShow();
				jsonpGet(util.server+'/forgetPassword',{phone: phone,actionId: this.actionId,vCode : vCode,newPassword: hex_md5(newPassword)},'forgetPassword',function(json){
					if(json.code == '1'){
						_this.closeForgetPassword();
						loadingRemove();
						_this.alertMsg('设置成功');
					}else{
						loadingRemove();
						_this.alertMsg('设置失败');
					}
				});
			}else{
				this.alertMsg();
			}*/
		},
		sendCaptcha:function(){
			var _this = this;
			var t = 60;
			var capTimer = function(){
				if(t > 0){
					$('.send-captcha').addClass('sended-captcha').text(t+'S后重发');
					t--;
				}else{
					clearInterval(_this.capTime);
					$('.send-captcha').removeClass('sended-captcha').text('获取验证码');
				}
			};
			this.actionId = null;
			var phone = $.trim($('input[name="fphone"]').val());
//			var reg = /^[1][0-9]{10}$/;	//1开头11位数字
			if(!$('.send-captcha').hasClass('sended-captcha')){
				//1003  reg.test(phone)
				if(phone.length>0 ){
					loadingShow();
					jsonpGet(util.NDNserver+'/getVCode',{phone: phone},'getVCode',function(json){
						if(json.code == '1'){
							$('.send-captcha').addClass('sended-captcha').text(t-- +'S后重发');
							_this.capTime = setInterval(capTimer,1000);
							_this.actionId = json.data;
							loadingRemove();
							commonAlert('发送成功');
						}else{
							loadingRemove();
							commonAlert(json.msg);
						}
					});
				}else{
					this.alertMsg('手机号输入有误');
				}
			}
		},
		alertMsg:function(text){
			this.$el.append(util.loadTpl($('#alertMsgTpl')));
			var w = $('#alertMsg .msg-board').width();
			var h = w*481/587;
			$('#alertMsg .msg-board').height(h);
			$('#alertMsg .msg-board').css({top: 'calc((100% - '+h+'px)/2)'});
			if(text)$('#alertMsg .msg-board .text').text(text);
		},
		closeMsg:function(){
			$('#alertMsg').remove();
		},
		toHome:function(){
			var _this = this;
			var phone = $.trim($('input[name="phone"]').val()),
				password = $.trim($('input[name="password"]').val());
//			var reg = /^[1][0-9]{10}$/;	//1开头11位数字
			if(!phone){
				this.alertMsg('请输入手机号');
				return;
			}
			if(!password){
				this.alertMsg('请输入密码');
				return;
			}
			loadingShow();
			$('body').append('<div class="gt"></div>');
			var handlerPopupMobile = function (captchaObj) {
		        // 将验证码加到id为captcha的元素里
		        captchaObj.appendTo(".gt");
		        //拖动验证成功后两秒(可自行设置时间)自动发生跳转等行为
		        captchaObj.onSuccess(function () {
		        	$(".gt").remove();
		            var validate = captchaObj.getValidate();
		            jsonpGet(
	            		util.NDNserver + "/userLogin", // 进行二次验证
		                {
		                    // 二次验证所需的三个值
		                	phone: phone,
		                	password: hex_md5(password),
		                    geetest_challenge: validate.geetest_challenge,
		                    geetest_validate: validate.geetest_validate,
		                    geetest_seccode: validate.geetest_seccode
		                },
		                'userLogin',
		                function (json) {
		                	if(json.code == '1'){
								var data = json.data;
								util.setCookie('user',JSON.stringify(data),1); 	//保存user到cookie
								if(_this.timer){
									window.clearInterval(_this.timer);
								}
								if(_this.capTime){
									window.clearInterval(_this.capTime);
								}
								Backbone.history.navigate('home',{trigger:true});
								$(".common-loading").remove();
							}else{
								$(".common-loading").remove();
								_this.alertMsg(json.msg);
							}
		                }
		            );
		        });
		        // 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
		    };
		    jsonpGet(
		        // 获取id，challenge，success（是否启用failback）
		        util.NDNserver + "/geetestRegister", 
		        {t: new Date().getTime()},	// 加随机数防止缓存
		        'geetestRegister',
		        function (json) {
		            // 使用initGeetest接口
		            // 参数1：配置参数
		            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
		        	var data = $.parseJSON(json.data);
		            initGeetest({
		                gt: data.gt,
		                challenge: data.challenge,
		                offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
		                // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
		            }, handlerPopupMobile);
		        }
		    );
			/*if(phone.length>0){
				loadingShow();
				jsonpGet(util.server+'/userLogin',{phone: phone,password: hex_md5(password)},'userLogin',function(json){
					if(json.code == '1'){
						var data = json.data;
						util.setCookie('user',JSON.stringify(data),1); 	//保存user到cookie
						if(_this.timer){
							window.clearInterval(_this.timer);
						}
						if(_this.capTime){
							window.clearInterval(_this.capTime);
						}
						Backbone.history.navigate('home',{trigger:true});
						loadingRemove();
					}else{
						loadingRemove();
						_this.alertMsg(json.msg);
					}
				});
			}else{
				this.alertMsg('手机号输入错误');
				return;
			}*/
		},
		setting:function(){
			var w = $('.loginBtn').width();
			var h = w*39/161;
			$('.loginBtn').css({height: h +'px','line-height': h-5 +'px'});
			var ih = $('.login-input').height();
			$('.forgetBtn').css({top: 'calc(100% - '+ih+'px - 2.23rem)'});
			
			var mun = 7;
			var logo = function(){
				mun--;
				switch (mun) {
				case 6:
					$('.logo').animate({top: '-8%'},600,'linear',logo);
					break;
				case 5:
					$('.logo').animate({top: '-15%'},200,'linear',logo);
					break;
				case 4:
					$('.logo').animate({top: '-8%'},160,'linear',logo);
					break;
				case 3:
					$('.logo').animate({top: '-11%'},120,'linear',logo);
					break;
				case 2:
					$('.logo').animate({top: '-8%'},90,'linear',logo);
					break;
				case 1:
					$('.logo').animate({top: '-10%'},65,'linear',logo);
					break;
				case 0:
					$('.logo').animate({top: '-8%'},50,'linear');
					break;

				}
			};
			setTimeout(logo,100);
		},
		getOs:function(){
			var userAgent = navigator.userAgent.toLowerCase();
			var mobile = userAgent.match(/(iphone|ipod|android|ios|ipad)/i);
			var isPC = !mobile;
			if(isPC){
				var ch = document.body.clientHeight;
				var w = ch*9/16;
				$('.login').css({width: w +'px'});
				$('.loginbg').css({width: w +'px'});
				$('.featherbg').css({width: w +'px'});
				$('.canvas').css({width: w +'px'});
			}
		},
		canvas :function(){
			var W,H,_this = this;
			W = $('#canvas').width();
			H = $('#canvas').height();
			window.onresize = function(){
				W = $('#canvas').width();
				H = $('#canvas').height();
			};
			var canvas = document.createElement("canvas");
			canvas.width = W;
			canvas.height = H;
			document.getElementById('canvas').appendChild(canvas);
			var ctx = canvas.getContext("2d");
			var particles = [{x: Math.round(0.6*W),y: Math.round(0.1*H),no:1},
			                 {x: Math.round(0.02*W),y: Math.round(0.4*H),no:2},
			                 {x: Math.round(0.75*W),y: Math.round(0.4*H),no:3},
			                 {x: Math.round(0.9*W),y: Math.round(0.5*H),no:4},
			                 {x: Math.round(0.12*W),y: Math.round(0.62*H),no:5},
			                 {x: Math.round(0.5*W),y: Math.round(0.65*H),no:6},
			                 {x: Math.round(0.2*W),y: Math.round(0.91*H),no:7}];

			var pw = 46;
			function draw(){
				ctx.clearRect(0, 0, W, H);	//清空画布
				ctx.beginPath();	//开始绘制
				for(var i = 0; i < particles.length; i++){
					var p = particles[i];
					var img = new Image();
					img.src = 'assets/images/login/f'+p.no+'.png';
					ctx.drawImage(img,p.x, p.y, pw, pw);
				}
				ctx.closePath(); //结束绘制
				ctx.fill();		//填充
			}
			
			var po = {x:0,y:0};
			function update(cpo){
				po.x += Math.round(cpo.g/10)/2;
				po.y += Math.round(cpo.b/10)/2;
				
				canvas.width = W;
				canvas.height = H;
				ctx.clearRect(0, 0, W, H);	//清空画布
				ctx.beginPath();	//开始绘制
				
				// for(var i = 0; i < particles.length; i++){
					// var p = particles[i];
					// var yw = (p.x+po.x)%W,
					// 	yh = (p.y+po.y)%H;
					// //1
					// if((yw < W-pw || yw > 0) && (yh < H-pw || yh > 0)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw, yh, pw, pw);
					// }
					// if((yw < W || yw > W-pw) && (yh < H-pw || yh > 0)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw-W, yh, pw, pw);
					// }
					// if((yw < -W+pw || yw > -W) && (yh < H-pw || yh > 0)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw+W, yh, pw, pw);
					// }
					// //2
					// if((yw < W-pw || yw > 0) && (yh < H || yh > H-pw)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw, yh-H, pw, pw);
					// }
					// if((yw < W || yw > W-pw) && (yh < H || yh > H-pw)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw-W, yh-H, pw, pw);
					// }
					// if((yw < -W+pw || yw > -W) && (yh < H || yh > H-pw)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw+W, yh-H, pw, pw);
					// }
					// //3
					// if((yw < W-pw || yw > 0) && (yh < -H+pw || yh > -H)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw, yh+H, pw, pw);
					// }
					// if((yw < W || yw > W-pw) && (yh < -H+pw || yh > -H)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw-W, yh+H, pw, pw);
					// }
					// if((yw < -W+pw || yw > -W) && (yh < -H+pw || yh > -H)){
					// 	var img = new Image();
					// 	img.src = 'assets/images/login/f'+p.no+'.png';
					// 	ctx.drawImage(img, yw+W, yh+H, pw, pw);
					// }
				// }
				ctx.closePath(); //结束绘制
				ctx.fill();		//填充
				
			}

			draw();	//初始化
			function fl(){
				update({g: 10,b: 0});
			}
			function orientationHandler(event) {
				if(event.gamma && event.beta){
					update({g: event.gamma,b: event.beta});
				}else{
					_this.timer = self.setInterval(fl,15);
				}
			}
			if (window.DeviceOrientationEvent) {
				window.addEventListener("deviceorientation", orientationHandler, false);
			}
		},
		hideGt: function(){
			$(".common-loading,.gt").remove();
		}
	});

	return View;
});